package com.esp.soccertutor.util;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.esp.soccertutor.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;



public class DownloadEpubBook extends AsyncTask<Void, Integer, Integer> {

	private Context context;
	private ProgressDialog mProgressDialog;
	private Activity activity;
	


	public DownloadEpubBook(Context context, Activity activity) {
		this.context = context;
		this.activity = activity;
	
	}

	@Override
	protected void onPreExecute() {

		mProgressDialog = new ProgressDialog(this.context);
		mProgressDialog.setMessage(context.getString(R.string.ProgressMessage));
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();
	}	

	@Override
	protected Integer doInBackground(Void... params) {
		int errorNo = 0;
//		if ((errorNo = this.downloadEpubFile(bookBean.getBOOKID())) == 0) {
//			if ((errorNo = this.downloadThumbnail(bookBean.getBOOKID())) == 0) {
//				errorNo = this.updateBookDB();
//			}
//		}
		return errorNo;
	}

	@Override
	protected void onPostExecute(Integer result) {
		mProgressDialog.dismiss();

		if (result == 0) {
			// Download Complete
			Toast.makeText(this.context,"Download Completed",Toast.LENGTH_LONG).show();
//			this.activity.startActivity(new Intent(this.context, BookListAll.class));
//			this.activity.finish();
			
		} else if (result == 100101){
			Toast.makeText(this.context,"Unable to downlaod book",Toast.LENGTH_LONG).show();
		} else if (result == 100102){
			Toast.makeText(this.context,"Download Book: No response from the server, please try after sometime...",Toast.LENGTH_LONG).show();
		} else if (result == 200101){
			Toast.makeText(this.context,"Unable to downlaod thumbnail",Toast.LENGTH_LONG).show();
		} else if (result == 200102){
			Toast.makeText(this.context,"Downlaod Thumbnail: No response from the server, please try after sometime...",Toast.LENGTH_LONG).show();
		} else if (result == 300101){
			Toast.makeText(this.context,"Error while updating the database...",Toast.LENGTH_LONG).show();
		}
	}

	public int downloadEpubFile(int bookid) {
		URL url = null;
		int errorNo = 0;
		HttpURLConnection conn = null;
		InputStream is = null;
		byte[] buffer = null;
		FileOutputStream fos = null;
		ByteArrayOutputStream bos = null;

		try {
			
			// set the download URL, a url that points to a file on the internet
			// this is the file to be downloaded
			url = new URL(Const.BOOK_URL + bookid + ".rar");
			// create the new connection
			conn = (HttpURLConnection) url.openConnection();

			if ((conn).getResponseCode() == HttpURLConnection.HTTP_OK) {
				// set up some things on the connection
				//conn.setRequestMethod("GET");
				//conn.setDoOutput(true);

				// and connect!
				conn.connect();

				int fileSize = conn.getContentLength();
				bos = new ByteArrayOutputStream(1);

				is = conn.getInputStream();

				System.out.println("total Size : " + fileSize);

				// set the path where we want to save the file in this case,
				// going to save it on the root directory of this sd card.
				// create a new file, specifying the path, and the filename
				// which we want to save the file as.
				Storage.veirfyLibPath();
				
				fos = new FileOutputStream(Const.LIB_DIR + "/" + bookid
						+ ".epub");
				
				buffer = new byte[2048];

				long downloaded = 0;
				int read = 0;
				while ((read = is.read(buffer)) != -1) {
					fos.write(buffer, 0, read);
					
					downloaded += read;
					
					this.publishProgress((int) ((downloaded * 80) / fileSize));				
				}
				
				this.publishProgress(85);

			} else {
				// no response from the server
				errorNo = 100102;
			}
		} catch (Exception e) {
			// Unable to download book
			errorNo = 100101;
			Log.error(this.getClass() + ":: downloadEpubFile()", e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}

			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}
			
			if (bos != null){
				try {
					bos.close();
				} catch (IOException e) {
				}
			}

			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}

		conn = null;
		is = null;
		fos = null;
		bos = null;
		buffer = null;
		url = null;

		return errorNo;
	}

	public int downloadThumbnail(int bookid) {

		URL url = null;
		int errorNo = 0;
		HttpURLConnection conn = null;
		InputStream is = null;
		byte[] buffer = null;
		FileOutputStream fos = null;
		ByteArrayOutputStream bos = null;

		try {
			// set the download URL, a url that points to a file on the internet
			// this is the file to be downloaded
			url = new URL(Const.THUMB_URL + bookid + ".png");
			// create the new connection
			conn = (HttpURLConnection) url.openConnection();

			if ((conn).getResponseCode() == HttpURLConnection.HTTP_OK) {
				// set up some things on the connection
				//conn.setRequestMethod("GET");
				//conn.setDoOutput(true);

				// and connect!
				conn.connect();

				int fileSize = conn.getContentLength();
				bos = new ByteArrayOutputStream(fileSize);

				is = conn.getInputStream();

				System.out.println("total Size : " + fileSize);

				buffer = new byte[1024];

				long downloaded = 0;
				int read = 0;
				while ((read = is.read(buffer)) != -1) {
					bos.write(buffer, 0, read);
					
					downloaded += read;
				}

				// set the path where we want to save the file in this case,
				// going to save it on the root directory of this sd card.
				// create a new file, specifying the path, and the filename
				// which we want to save the file as.
				Storage.veirfyLibPath();
				
				fos = new FileOutputStream(Const.LIB_DIR + "/" + bookid
						+ ".png");

				fos.write(bos.toByteArray());
				
				this.publishProgress(90);

			} else {
				// no response from the server
				errorNo = 200102;
			}
		} catch (Exception e) {
			// Unable to downaload thumbnail
			errorNo = 200101;
			Log.error(this.getClass() + ":: downloadEpubFile()", e);
		} finally {
			if (conn != null) {
				conn.disconnect();
			}

			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
				}
			}

			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
			
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
				}
			}			
		}

		conn = null;
		is = null;
		fos = null;
		bos = null;
		buffer = null;
		url = null;

		return errorNo;
	}
	
	public int updateBookDB(){
		int errorNo = 0;
		//INSERT INTO DATABASE 
		
		try{
			
						
		}catch(Exception e){
			//Unable update database
			errorNo = 100301;
			
			Log.error(this.getClass() + " :: updateBookDB()", e);
		}

		this.publishProgress(100);
		
	
		
		return errorNo;
	}
		
	@Override
	protected void onProgressUpdate(Integer... vals) {
        mProgressDialog.setProgress(vals[0]);
   }

}
